package domain.service;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.io.UnsupportedEncodingException;

import domain.model.Domain;

public class GooglePageRank {
	public GooglePageRank(Domain domain)
	{
		String message = null;
		try {
			message = URLEncoder.encode(domain.getName(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

        try {
        	
            URL url = new URL("http://gpagerank.net/pr.jsp?url=http://"+message+"&f=text");
    		
    		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(500000);
    		connection.setConnectTimeout(1000000);
    		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("iso-8859-1")));
    
        	 String content = "";
        	 while(1==1)
 			 {
 				 String str = reader.readLine();
 				 if(str==null) break;
 				 content+=str;   				
 			 }
        	
        	 int googlePageRank = 0;
        	 if(content != "")
        	 {
        		 googlePageRank = Integer.parseInt(content);
        	 }
		 	 
     		domain.setRankGoogle(googlePageRank);
		 
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

	}
//	public static void main( String args[])
//	{
//		new GooglePageRank("google.com");
//	}
}
